<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2019/11/29
 * Time: 15:23
 */

namespace app\api\controller\deliver\v1;


use app\api\controller\deliver\v1\Visa;
use app\api\model\Capital;
use app\api\model\DiagnosticField;
use app\api\model\SchemeCharacteristic;
use app\api\model\SchemeImg;
use app\api\model\schemeMaster;
use app\api\model\SchemeTag;
use think\Controller;
use think\Request;
use app\api\model\Authority;


class QuickQuotation extends Controller
{
    protected $us;
    
    public function _initialize()
    {
        $this->us = Authority::check(1);
    }
    
    /**
     * @param array $data
     * @return array
     * $data=['id','name'=>'123']  id必填，name选填，默认值为123（有默认值时key不能为int）
     */
    public static function param(array $data)
    {
        if (empty($data)) {
            r_date([], 300, '提交数据不正确');
        }
        $return = [];
        
        foreach ($data as $key => $item) {
            
            if (!is_int($key)) {
                
                $val = Request::instance()->post($key);
                $get = Request::instance()->get($key);
                if (isset($val) || isset($get)) {
                    $return[$key] = isset($val) ? trim($val) : trim($get);
                    
                } else {
                    $return[$key] = trim($item);
                }
            } else {
                $val = Request::instance()->post($item);
                $get = Request::instance()->get($item);
                
                if (!isset($val) && !isset($get)) {
                    r_date([], 300, "缺少参数");
                }
                $return[$item] = isset($val) ? trim($val) : $get;
            }
        }
        return $return;
    }
    /*
     * 判断条方案大师还是基建
     */
    public function jumpToPage()
    {
        $request                        = Authority::param(['orderNo']);
        if(is_numeric($request['orderNo'])){
            r_date(['orderNo'=>$request['orderNo'],'type'=>1],200);
        }else{
            $plan_id=db('scheme_master',config('database.zong'))->where('scheme_no',$request['orderNo'])->value('plan_id');
            r_date(['orderNo'=>$plan_id,'type'=>2],200);
        }
      
    }
    
    /*
     * 附近的订单
     */
    public function oldQuickGetList($order_no)
    {
        $op=null;
        // $op   = db('order')->where(['order.order_id' =>$order_no])
        //     ->join('sign', 'order.order_id=sign.order_id', 'left')
        //     ->field('sign.sign_id,sign.username,sign.idnumber,sign.contract,sign.addtime,sign.uptime,sign.addres,sign.contractpath,sign.agency_img,sign.ding,sign.zhong,sign.wei,sign.b1,sign.b2,sign.explain,order.contacts,order.order_id,order.quotation')
        //     ->find();
        
        if ($op) {
            $op['username']   = $op['contacts'];
            $op['idnumber']   = !empty($op['idnumber']) ? $op['idnumber'] : null;
            $op['contract']   = !empty($op['contract']) ? $op['contract'] : null;
            $op['type']       = !empty($op['contractpath']) ? 1 : 2;
            $op['addtime']    = !empty($op['addtime']) ? date('Y-m-d H:i', $op['addtime']) : null;
            $op['uptime']     = !empty($op['uptime']) ? date('Y-m-d H:i', $op['uptime']) : null;
            $op['addres']     = !empty($op['addres']) ? $op['addres'] : null;
            $op['quotation']  = !empty($op['quotation']) ? $op['quotation'] : '';
            $op['agency_img'] = !empty($op['agency_img']) ? $op['agency_img'] : '';
            $envelopes        = db('envelopes')->where(['ordesr_id' => $op['order_id'], 'type' => 1])->find();
            if ($envelopes) {
                $agency  = [];
                $sumlist = [];
                $capital = db('capital')->where(['envelopes_id' => $envelopes['envelopes_id'], 'types' => 1])
                    ->field('projectId,capital_id,class_a,class_b as projectTitle,company,square,
            un_Price as projectMoney,to_price,fen as category,agency,projectRemark as remarks')->select();
                foreach ($capital as $item) {
                    if ($item['agency'] == 1) {
                        $agency[] = $item;
                    } else {
                        $sumlist[] = $item;
                    }
                    
                }
                $envelopes['agencysum'] = $s = array_sum(array_column($agency, 'to_price'));
                $envelopes['sumlist']   = array_sum(array_column($sumlist, 'to_price'));
                $s                      = implode(',', array_column($capital, 'capital_id'));
                $yc                     = empty($envelopes['through_id']) ? 1 : 2;
                $allow                  = db('allow')->where(['order_id' => $op['order_id'], 'capital_id' => $s, 'envelopes_id' => $envelopes['envelopes_id'], 'yc' => $yc])->value('id');
                
                $envelopes['allow'] = $allow['id'];
                
                $envelopes['give_b'] = null;
                
                if ($envelopes['capitalgo']) {
                    $envelopes['capitalgo'] = unserialize($envelopes['capitalgo']);
                } else {
                    $envelopes['capitalgo'] = null;
                }
                $envelopes['project_title'] = empty($envelopes['project_title']) ? '报价方案' : $envelopes['project_title'];
                $envelopes['yc']            = $yc;
                
                //质保卡
                $warranty_collection = \db('warranty_collection')->where('warranty_collection.envelopes_id', $envelopes['envelopes_id'])->where('warranty_collection.pro_types', 0)->join('warranty', 'warranty.id=warranty_collection.warranty_id', 'left')->where('warranty_collection.order_id', $op['order_id'])->field('warranty.title,warranty_collection.years,warranty_collection.type,warranty_collection.warranty_id,warranty_collection.id')->select();
                //交互标准
//                $capitalList = $capital;
//                foreach ($capitalList as $k => $item) {
//                    $capitalList[$k]['class_b'] = $item['projectTitle'];
//                    $po                         = db('auxiliary_project_list')->where('capital_id', $item['capital_id'])->whereNull('delete_time')->field('auxiliary_id,id')->select();
//                    $auxiliary_ids              = array_unique(array_column($po, 'id'));
//                    if ($po) {
//                        foreach ($po as $l => $key) {
//
//                            $capitalList[$k]['auxiliary_id']  = $item['projectId'];
//                            $capitalList[$k]['auxiliary_ids'] = implode($auxiliary_ids, ',');
//                            $capitalList[$k]['data'][]        = db('auxiliary_interactive')->where('id', $key['auxiliary_id'])->field('id,title')->find();
//                            $auxiliary_interactive            = db('auxiliary_interactive')
//                                ->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.auxiliary_interactive_id=auxiliary_interactive.id', 'left')
//                                ->where('auxiliary_delivery_schedule.auxiliary_project_list_id', $key['id'])
//                                ->whereNull('auxiliary_delivery_schedule.delete_time')
//                                ->field('auxiliary_interactive.id, auxiliary_interactive.title, auxiliary_delivery_schedule.id as auxiliary_delivery_schedule_id')->select();
//                            foreach ($auxiliary_interactive as $p => $value) {
//                                $auxiliary_delivery_node = db('auxiliary_delivery_node')->where('auxiliary_delivery_schedul_id', $value['auxiliary_delivery_schedule_id'])->field('state,node_id')->select();
//                                $auxiliaryNodeId         = array_column($auxiliary_delivery_node, 'state');
//                                $auxiliaryNodeNode       = array_column($auxiliary_delivery_node, 'node_id');
//                                if ($auxiliaryNodeId) {
//                                    if (in_array(2, $auxiliaryNodeId)) {
//                                        $auxiliary_interactive[$p]['state']   = 2;
//                                        $auxiliary_interactive[$p]['node_id'] = implode(',', $auxiliaryNodeNode);
//
//                                    } elseif (in_array(0, $auxiliaryNodeId)) {
//                                        $auxiliary_interactive[$p]['state']   = 0;
//                                        $auxiliary_interactive[$p]['node_id'] = implode(',', $auxiliaryNodeNode);
//
//                                    } else {
//                                        $auxiliary_interactive[$p]['state']   = 1;
//                                        $auxiliary_interactive[$p]['node_id'] = implode(',', $auxiliaryNodeNode);
//                                    }
//                                } else {
//                                    $auxiliary_interactive[$p]['state']   = 3;
//                                    $auxiliary_interactive[$p]['node_id'] = 0;
//                                }
//
//
//                            }
//                            $capitalList[$k]['data'][$l]['data'] = array_merge($auxiliary_interactive);
//                        }
//                    } else {
//                        $capitalList[$k]['data'] = [];
//                    }
//
//                }
                $op = ['gong' => $envelopes, 'company' => $capital, 'warranty_collection' => $warranty_collection, 'capitalList' => null];
                r_date($op, 200);
            } else {
                r_date(null, 300, '暂未找到报价');
            }
            
            
        } else {
            r_date(null, 300, '暂未找到报价');
        }
        
        
    }
    /**
     * 新版快速报价页面数据
     */
    public function QuickGetList(Capital $capitals)
    {
        $data = Request::instance()->get();
        
        $order_no=$data['order_no'];
        $op   = db('order')->where(['order.order_no' => $order_no])->find();
        
        if ($op) {
            $envelopes = db('envelopes')->where(['ordesr_id' => $op['order_id'], 'type' => 1])->find();
            if ($envelopes) {
                $agency      = [];
                $sumlist     = [];
                $result      = array();
                $capital     = $capitals->with('specsList')
                    ->where(['envelopes_id' => $envelopes['envelopes_id'], 'types' => 1])
                    ->field('projectId,capital_id,class_a,class_b as projectTitle,company,square, un_Price as projectMoney,to_price as allMoney,fen as types,agency,projectRemark as remarks,categoryName,rule as sectionTitle,sort,capital.small_order_fee as smallOrderFee')->select();
                $capitalList = $capital;
                
                $envelopes['order_list'] = db('order')->where(['order_id' => $data['order_id']])->field('order_id,state')->find();
                $envelopes['give_b']    = null;
                if ($envelopes['capitalgo']) {
                    $envelopes['capitalgo'] = unserialize($envelopes['capitalgo']);
                } else {
                    $envelopes['capitalgo'] = null;
                }
                $envelopes['project_title'] = empty($envelopes['project_title']) ? '报价方案' : $envelopes['project_title'];
                
                
                //质保卡
                $warranty_collection = \db('warranty_collection')->where('warranty_collection.envelopes_id', $envelopes['envelopes_id'])->where('warranty_collection.pro_types', 0)->join('warranty', 'warranty.id=warranty_collection.warranty_id', 'left')->where('warranty_collection.order_id', $op['order_id'])->field('warranty.title,warranty_collection.years,warranty_collection.type,warranty_collection.warranty_id,warranty_collection.id')->select();
                //交互标准

//                $capital_id = array_column($capitalList, 'capital_id');
//
//                $po = db('auxiliary_project_list')->whereIn('capital_id', $capital_id)->whereNull('delete_time')->field('auxiliary_id,id,capital_id')->select();
//
//                $auxiliary_id          = array_column($po, 'auxiliary_id');
//                $auxiliary_interactive = [];
//                if (!empty($auxiliary_id)) {
//                    $auxiliary_interactive = db('auxiliary_interactive')->whereIn('id', $auxiliary_id)->field('id,title')->select();
//                }
//                $id                       = array_column($po, 'id');
//                $auxiliaryInteractiveList = db('auxiliary_interactive')
//                    ->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.auxiliary_interactive_id=auxiliary_interactive.id', 'left')
//                    ->whereIn('auxiliary_delivery_schedule.auxiliary_project_list_id', $id)
//                    ->whereNull('auxiliary_delivery_schedule.delete_time')
//                    ->field('auxiliary_interactive.id, auxiliary_interactive.title, auxiliary_delivery_schedule.id as auxiliary_delivery_schedule_id,auxiliary_delivery_schedule.auxiliary_project_list_id')->select();
//                if (!empty($auxiliaryInteractiveList)) {
//                    $auxiliary_delivery_node = db('auxiliary_delivery_node')->whereIn('auxiliary_delivery_schedul_id', array_column($auxiliaryInteractiveList, 'auxiliary_delivery_schedule_id'))->field('state,node_id,auxiliary_delivery_schedul_id')->select();
//                }
//                $capitalListArray = [];
//                $agency           = [];
//                $sumlist          = [];
//                foreach ($capitalList as $k => $item) {
//                    if ($item['agency'] == 1) {
//                        $agency[] = $item;
//                    } else {
//                        $sumlist[] = $item;
//                    }
//                    $auxiliary_ids = array_unique(array_column($po, 'id'));
//                    if ($po) {
//                        foreach ($po as $l => $key) {
//                            if ($item['capital_id'] == $key['capital_id']) {
//                                $capitalListArray[$k]['class_b']       = $item['projectTitle'];
//                                $capitalListArray[$k]['auxiliary_id']  = $item['projectId'];
//                                $capitalListArray[$k]['auxiliary_ids'] = implode($auxiliary_ids, ',');;
//                                foreach ($auxiliary_interactive as $val) {
//                                    if ($key['auxiliary_id'] == $val['id']) {
//                                        $auxiliaryList[] = $val;
//                                    }
//
//                                }
//                                foreach ($auxiliaryList as $ls) {
//                                    $auxiliaryInteractiveListNode = [];
//
//                                    foreach ($auxiliaryInteractiveList as $p => $value) {
//                                        if ($key['id'] == $value['auxiliary_project_list_id'] && $key['id'] == $value['auxiliary_project_list_id']) {
//                                            $state   = 3;
//                                            $node_id = 0;
//                                            foreach ($auxiliary_delivery_node as $node) {
//                                                if ($node['auxiliary_delivery_schedul_id'] == $value['auxiliary_delivery_schedule_id'] && $key['id'] == $value['auxiliary_project_list_id']) {
//                                                    $auxiliaryNodeId   = array_column($auxiliary_delivery_node, 'state');
//                                                    $auxiliaryNodeNode = array_column($auxiliary_delivery_node, 'node_id');
//                                                    if ($auxiliaryNodeId) {
//                                                        if (in_array(2, $auxiliaryNodeId)) {
//                                                            $state   = 2;
//                                                            $node_id = implode(',', $auxiliaryNodeNode);
//                                                        } elseif (in_array(0, $auxiliaryNodeId)) {
//                                                            $state   = 0;
//                                                            $node_id = implode(',', $auxiliaryNodeNode);
//                                                        } else {
//                                                            $state   = 1;
//                                                            $node_id = implode(',', $auxiliaryNodeNode);
//                                                        }
//                                                    } else {
//                                                        $state   = 3;
//                                                        $node_id = 0;
//                                                    }
//                                                }
//                                            }
//                                            $auxiliaryInteractiveListNode[$p]['state']                          = $state;
//                                            $auxiliaryInteractiveListNode[$p]['node_id']                        = $node_id;
//                                            $auxiliaryInteractiveListNode[$p]['id']                             = $value['id'];
//                                            $auxiliaryInteractiveListNode[$p]['title']                          = $value['title'];
//                                            $auxiliaryInteractiveListNode[$p]['auxiliary_delivery_schedule_id'] = $value['auxiliary_delivery_schedule_id'];
//                                            $auxiliaryInteractiveListNode[$p]['auxiliary_project_list_id']      = $value['auxiliary_project_list_id'];
//                                        }
//
//                                        $ls['data'] = array_merge($auxiliaryInteractiveListNode);
//                                    }
//                                }
//                                $capitalListArray[$k]['data'][] = $ls;
//                            }
//                        }
//
//                    } else {
//                        $capitalListArray[$k]['data'] = [];
//                    }
//
//                }
                foreach ($capital as $item) {
                    $detailed=db('detailed')->where('detailed_id',$item['projectId'])->field('warranty_years as warrantYears,warranty_text_1 as warrantyText1,warranty_text_2 as exoneration,display')->find();
                    if(!empty($detailed['warrantYears']) &&  $detailed['warrantYears'] !='0.00'){
                        $item['isWarranty'] =1;
                        $item['warranty'] = [
                            'warrantYears'=>$detailed['warrantYears'],
                            'warrantyText1'=>$detailed['warrantyText1'],
                            'exoneration'=>$detailed['exoneration'],
                        ];
                    }else{
                        $item['warranty'] =null;
                        $item['isWarranty'] =0;
                    }
                    $item['specsList'] = $item['specs_list'];
                    unset($item['specs_list']);
                    if ($item['agency'] == 1) {
                        $agency[] = $item;
                    } else {
                        $sumlist[] = $item;
                    }
                    $item['smallOrderFeeType'] = 1;
                    if ($item['smallOrderFee'] == '0.00') {
                        $item['smallOrderFeeType'] = 2;
                    }
                    $item['artificialTag'] = 0;
                    if (!empty($item['sectionTitle'])) {
                        $item['artificialTag'] = 1;
                    }
                    $result[$item['categoryName']][] = $item;
                    
                }
                foreach ($result as $k => $list) {
                    $schemeTag['title'] = $k;
                    $schemeTag['data']  = $result[$k];
                    $tageList[]         = $schemeTag;
                }
                if($envelopes['products_main_discount_money'] !=0){
                    $envelopes['give_money'] =  $envelopes['give_money']-$envelopes['products_main_discount_money'];
                    $envelopes['products_main_discount_money']=0;
                }
                if($envelopes['products_purchasing_discount_money'] !=0){
                    $envelopes['purchasing_discount'] =  $envelopes['purchasing_discount']-$envelopes['products_purchasing_discount_money'];
                    $envelopes['products_purchasing_discount_money']=0;
                }
                $envelopes['capital_list'] = $tageList;
                $envelopes['envelopes_id']      = 0;
                $envelopes['products']      = [];
                $envelopes['selectType']      = 2;
                $envelopes['agencysum'] = $s = array_sum(array_column(array_unique($agency), 'allMoney'));
                $envelopes['sumlist']   = array_sum(array_column(array_unique($sumlist), 'allMoney'));
                $envelopes['group']              = $envelopes['groupss'];
                r_date(['company' => $envelopes, 'warranty_collection' => $warranty_collection, 'capitalList' => null], 200);
            } else {
                r_date(null, 300, '暂未找到报价');
            }
            
            
        } else {
            r_date(null, 300, '暂未找到报价');
        }
        
        
    }
    
    public function QuestionName()
    {
        
        $data = static::param(['order_id']);
        $re   = db('order')->field('order.pro_id,go.title')
            ->join('goods_category go', 'order.pro_id=go.id', 'left')
            ->where('order.order_id', $data['order_id'])
            ->find();
        r_date($re, 200);
    }
    
    /*
     * 上门诊断
     *
     */
    public function diagnosticRecord(DiagnosticField $diagnosticField)
    {
        $data = static::param(['problemId']);
        $rows = $diagnosticField
            ->where('difference', $data['problemId']);
        if ($data['problemId'] == 3) {
            $rows->where('type', 18);
        }
        if ($data['problemId'] == 104) {
            $rows->where('type', 32);
        }
        if ($data['problemId'] == 42) {
            $rows->whereIn('type', [7, 8, 9, 10]);
        }
        $rows     = $rows->field('id,title,moreChoice,type,headline,log,click,sort')
            ->order('sort asc')
            ->select();
        $tageList = [];
        if ($rows) {
            $result = array();
            foreach ($rows as $k => $v) {
                if (!empty($v['log'])) {
                    $v['log'] = unserialize($v['log']);
                }
                
                $result[$v['headline']][] = $v;
            }
            
            foreach ($result as $k => $list) {
                $schemeTag['title']      = $k;
                $schemeTag['type']       = $list[0]['type'];
                $schemeTag['moreChoice'] = $list[0]['moreChoice'];
                $schemeTag['data']       = $result[$k];
                unset($rows['position']);
                $tageList[] = $schemeTag;
            }
            
        }
        
        
        r_date($tageList, 200);
    }
    
    public function subordinate(DiagnosticField $diagnosticField)
    {
        $data     = static::param(['problemId', 'id', 'childId']);
        $p        = 0;
        $tageList = [];
        $childId  = json_decode($data['childId'], true);
        if ($data['problemId'] == 42 && (count($childId) == 4 || count($childId) == 6)) {
            $rows = \db('diagnostic_record', config('database.zong'))->where(['goods_category_id' => $data['problemId']])->select();
            
            
            foreach ($childId as $item) {
                if ($item['type'] == 7 || $item['type'] == 8) {
                    $diagnosis[] = $item;
                }
                if ($item['type'] == 8 || $item['type'] == 11 || $item['type'] == 12) {
                    $diagnosisArray[] = $item;
                }
                
            }
            foreach ($rows as $l => $list) {
                $diagn               = [];
                $array               = array_column($diagnosis, 'id');
                $diagnostic_relation = \db('diagnostic_relation', config('database.zong'))->where(function ($quer) {
                    $quer->where('diagnostic_relation.type', 7)->whereOr('diagnostic_relation.type', 8);
                })->join('diagnostic_field', 'diagnostic_field.id=diagnostic_relation.position', 'left')->where(['diagnostic_record_id' => $list['id']])->field('diagnostic_field.title,diagnostic_relation.type,diagnostic_relation.result,diagnostic_relation.position,diagnostic_record_id')->order('diagnostic_field.sort asc')->select();
                $diagnostiId         = implode(',', array_unique(array_column($diagnostic_relation, 'position')));
                
                if ($diagnostiId == implode(',', $array)) {
                    if ($diagnostic_relation[0]['result'] == 0) {
                        $p = $list['id'];
                        continue;
                    } elseif ($diagnostic_relation[0]['result'] == 2) {
                        
                        if (count(array_column($diagnosisArray, 'id')) == 3) {
                            
                            $array1               = implode(',', array_column($diagnosisArray, 'id'));
                            $diagnostic_relation1 = \db('diagnostic_relation', config('database.zong'))->join('diagnostic_field', 'diagnostic_field.id=diagnostic_relation.position', 'left')->where(['diagnostic_record_id' => $list['id']])->where('diagnostic_relation.type', '<>', 7)->field('diagnostic_field.title,diagnostic_relation.type,diagnostic_relation.result,diagnostic_relation.position,diagnostic_record_id')->order('diagnostic_field.sort asc')->select();
                            $result               = array_merge(array_unique(array_column($diagnostic_relation1, 'result')));
                            $result               = $result[count($result) - 1];
                            
                            foreach ($diagnostic_relation1 as $o) {
                                if ($o['type'] == 8 || $o['type'] == 11 || $o['type'] == 12) {
                                    $diagn[] = $o['position'];
                                }
                            }
                            $diagnostiId2 = implode(',', $diagn);
                            
                            if ($diagnostiId2 == $array1) {
                                if ($result == 0) {
                                    $p = $list['id'];
                                    continue;
                                }
                            }
                        }
                        
                        
                    }
                }
            }
        }
        if ($data['problemId'] == 42 || $data['problemId'] == 3 || $data['problemId'] == 104) {
            $rows = $diagnosticField
                ->where('difference', $data['problemId']);
            if ($data['problemId'] == 3) {
                if ($data['id'] == 57) {
                    $rows->whereNotIn('type', [28, 29]);
                } else {
                    $rows->whereIn('type', [28, 29]);
                }
                $rows->where('type', '<>', 18);
            }
            if ($data['problemId'] == 104) {
                if ($data['id'] == 127) {
                    $rows->where('type', 30);
                } else {
                    $rows->where('type', 31);
                }
                $rows->where('type', '<>', 32);
            }
            
            if ($data['problemId'] == 42) {
                if (count($childId) > 3) {
                    if (count($childId) > 0 && count($childId) <= 5) {
                        if ($p != 0) {
                            $rows->whereIn('type', [7, 8, 9, 10]);
                        } else {
                            $rows->whereIn('type', [7, 8, 9, 10, 11, 12]);
                        }
                        
                    } elseif (count($childId) >= 6) {
                        if ($p != 0) {
                            $rows->whereIn('type', [7, 8, 9, 10, 11, 12]);
                        } else {
                            $rows->whereIn('type', [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]);
                        }
                        
                    }
                } else {
                    $rows->whereIn('type', [7, 8, 9, 10]);
                }
            }
            
            $rows = $rows->field('id,title,moreChoice,type,headline,log,click,sort')
                ->order('sort asc')
                ->select();
            if ($rows) {
                $result = array();
                foreach ($rows as $k => $v) {
                    if (!empty($v['log'])) {
                        $v['log'] = unserialize($v['log']);
                    }
                    
                    
                    $result[$v['headline']][] = $v;
                }
                
                foreach ($result as $k => $list) {
                    $schemeTag['title']      = $k;
                    $schemeTag['type']       = $list[0]['type'];
                    $schemeTag['moreChoice'] = $list[0]['moreChoice'];
                    $schemeTag['data']       = $result[$k];
                    unset($rows['position']);
                    $tageList[] = $schemeTag;
                }
                
            }
            
        }
        
        
        r_date($tageList, 200);
    }
    
    /*
     * 数据匹配
     */
    public function matching(schemeMaster $schemeMaster)
    {
        
        $data    = static::param(['childId', 'mainId', 'lat', 'lng', 'order_id']);
        
        $childId = json_decode($data['childId'], true);
        $row     = null;
        foreach ($childId as $item) {
            db('basic_selection', config('database.zong'))->insert(['position' => $item['id'], 'title' => $item['title'], 'type' => $item['type'], 'order_id' => $data['order_id'], 'cleared_time' => time(), 'goods_category_id' => $data['mainId']]);
        }
        
        $diagnostic_record = \db('diagnostic_record', config('database.zong'))->where(['goods_category_id' => $data['mainId']])->select();
        if ($diagnostic_record) {
            $Present        = '';
            $diagnosis      = [];
            $diagnosisArray = [];
            foreach ($childId as $item) {
                if ($item['type'] == 5) {
                    $Present = $item['id'];
                }
                if ($item['type'] == 7 || $item['type'] == 8 || $item['type'] == 18 || $item['type'] == 19) {
                    $diagnosis[] = $item;
                }
                if ($item['type'] == 8 || $item['type'] == 11 || $item['type'] == 12) {
                    $diagnosisArray[] = $item;
                }
                if ($item['type'] == 13 || $item['type'] == 14 || $item['type'] == 15 || $item['type'] == 16 || $item['type'] == 17) {
                    $diagnosisArrayList[] = $item;
                }
            }
            
            $size = [];
            foreach ($diagnostic_record as $l => $list) {
                $diagn = [];
                if ($Present) {
                    $diagnostic_relation = \db('diagnostic_relation', config('database.zong'))->join('diagnostic_field', 'diagnostic_field.id=diagnostic_relation.position', 'left')->where(['diagnostic_relation.position' => $Present, 'diagnostic_relation.diagnostic_record_id' => $list['id']])->order('diagnostic_field.sort asc')->field('diagnostic_field.title')->find();
                    if ($diagnostic_relation) {
                        $diagnosticId = \db('diagnostic_relation', config('database.zong'))->join('diagnostic_field', 'diagnostic_field.id=diagnostic_relation.position', 'left')->where(['diagnostic_relation.diagnostic_record_id' => $list['id']])->order('diagnostic_field.sort asc')->field('diagnostic_field.title')->select();
                        $last_names   = array_column($childId, 'sort');
                        array_multisort($last_names, SORT_ASC, $childId);
                        $matches = implode(',', array_column($diagnosticId, 'title'));
                        $mat     = implode(',', array_column($childId, 'title'));
                        
                        $size[$l]['similarity'] = similar_text($matches, $mat);
                        $size[$l]['id']         = $list['id'];
                    } else {
                        $size[$l]['similarity'] = 0;
                        $size[$l]['id']         = $list['id'];
                    }
                    
                } else {
                    
                    $array               = array_column($diagnosis, 'id');
                    $diagnostic_relation = \db('diagnostic_relation', config('database.zong'))->where(function ($quer) {
                        $quer->where('diagnostic_relation.type', 7)->whereOr('diagnostic_relation.type', 8)->whereOr('diagnostic_relation.type', 18)->whereOr('diagnostic_relation.type', 19);
                    })->join('diagnostic_field', 'diagnostic_field.id=diagnostic_relation.position', 'left')->where(['diagnostic_record_id' => $list['id']])->field('diagnostic_field.title,diagnostic_relation.type,diagnostic_relation.result,diagnostic_relation.position,diagnostic_record_id')->order('diagnostic_field.sort asc')->select();
                    
                    $diagnostiId = implode(',', array_unique(array_column($diagnostic_relation, 'position')));
                    
                    if ($diagnostiId == implode(',', $array)) {
                        $size[$l]['similarity'] = 4;
                        if ($diagnostic_relation[0]['result'] == 2) {
                            $array1               = implode(',', array_column($diagnosisArray, 'id'));
                            $diagnostic_relation1 = \db('diagnostic_relation', config('database.zong'))->join('diagnostic_field', 'diagnostic_field.id=diagnostic_relation.position', 'left')->where(['diagnostic_record_id' => $list['id']])->where('diagnostic_relation.type', '<>', 7)->field('diagnostic_field.title,diagnostic_relation.type,diagnostic_relation.result,diagnostic_relation.position,diagnostic_record_id')->order('diagnostic_field.sort asc')->select();
                            $result               = array_merge(array_unique(array_column($diagnostic_relation1, 'result')));
                            $result               = $result[count($result) - 1];
                            
                            if ($result == 2) {
                                
                                $array2               = implode(',', array_column($diagnosisArray, 'id'));
                                $diagnostic_relation2 = \db('diagnostic_relation', config('database.zong'))->join('diagnostic_field', 'diagnostic_field.id=diagnostic_relation.position', 'left')->where(['diagnostic_record_id' => $list['id']])->whereIn('diagnostic_relation.type', [13, 14, 15, 16, 17])->field('diagnostic_field.title,diagnostic_relation.type,diagnostic_relation.result,diagnostic_relation.position,diagnostic_record_id')->order('diagnostic_field.sort asc')->select();
                                if ($diagnostic_relation) {
                                    $diagnostiId1 = implode(',', array_unique(array_column($diagnostic_relation2, 'position')));
                                    if ($diagnostiId1 == $array2) {
                                        $size[$l]['similarity'] = 11;
                                    } else {
                                        $size[$l]['similarity'] = 0;
                                    }
                                } else {
                                    $size[$l]['similarity'] = 0;
                                }
                            } elseif ($diagnostic_relation1 && $result != 1) {
                                
                                
                                foreach ($diagnostic_relation1 as $o) {
                                    if ($o['type'] == 8 || $o['type'] == 11 || $o['type'] == 12) {
                                        $diagn[] = $o['position'];
                                    }
                                }
                                
                                $diagnostiId2 = implode(',', $diagn);
                                
                                if ($diagnostiId2 == $array1) {
                                    $size[$l]['similarity'] = 6;
                                } else {
                                    $size[$l]['similarity'] = 0;
                                }
                            } elseif ($result == 1) {
                                
                                $size[$l]['id']         = 0;
                                $size[$l]['similarity'] = 10;
                                break;
                            }
                        } elseif ($diagnostic_relation[0]['result'] == 1) {
                            
                            $size[$l]['id']         = 0;
                            $size[$l]['similarity'] = 10;
                            break;
                        }
                        
                        $size[$l]['id'] = $diagnostic_relation[0]['diagnostic_record_id'];
                    }
                    
                    
                }
                
                
            }
            
            $last = array_column($size, 'similarity');
            array_multisort($last, SORT_DESC, $size);
            if (!empty($size) && $this->us['in_business']==1) {
                $plan_id           = \db('scheme_relation', config('database.zong'))->where(['diagnostic_record_id' => $size[0]['id']])->column('plan_id');
                $diagnostic_record = \db('diagnostic_record', config('database.zong'))->where(['id' => $size[0]['id']])->field('title,reminders')->find();
                $rows = $schemeMaster
                    ->with(['schemeProject', 'schemeProject.specsList'])
                    ->with('schemeImg')
                    ->with('schemeTag')
                    ->with('schemeCharacteristic')
                    ->whereIn('scheme_master.plan_id', $plan_id)
                    ->where('scheme_master.state', 1)
                    ->field('scheme_master.plan_id,scheme_master.name,scheme_master.info,scheme_master.day,scheme_master.reminde,scheme_master.pricing_rules,scheme_master.service_content,scheme_master.materials_used,scheme_master.service_duration,scheme_master.completion,scheme_master.quality')
                    ->limit(4)
                    ->select();
                
                if ($rows) {
                    foreach ($rows as $k1=>$item) {
                        $rows[$k1]['selectType']      = 1;
                        $tageList = [];
                        if ($item['scheme_tag']) {
                            $result = array();
                            foreach ($item['scheme_tag'] as $k => $v) {
                                $result[$v['pid']][] = $v;
                            }
                            
                            foreach ($result as $k => $list) {
                                $schemeTag['id'] = $k;
                                
                                $schemeTag['position'] = $result[$k];
                                unset($item['scheme_tag']);
                                $tageList[] = $schemeTag;
                            }
                        }
                        
                        if ($item['scheme_project']) {
                            $title  = array_unique(array_column($item['scheme_project'], 'grouping'));
                            $result = array();
                            foreach ($title as $key => $info) {
                                foreach ($item['scheme_project'] as $it) {
                                    $it['specsList'] = $it['specs_list'];
                                    $it['allMoney']  = $it['to_price'];
                                    $it['types']     = 4;
                                    unset($it['specs_list']);
                                    if ($info == $it['grouping']) {
                                        $result[$key]['title']  = $info;
                                        $result[$key]['id']     = 0;
                                        $result[$key]['data'][] = $it;
                                    }
                                    
                                }
                            }
                            
                        }
                        
                        unset($item['scheme_project']);
                        $item['scheme_project'] = array_merge($result);
                        
                        
                    }
                    
                    $array                  = $this->getAround($data['lng'], $data['lat'], 5000);
                    $condition['order.lng'] = array(array('EGT', $array['minLng']), array('ELT', $array['maxLng']), 'and');//(`longitude` >= minLng) AND (`longitude` <= maxLng)
                    $condition['order.lat'] = array(array('EGT', $array['minLat']), array('ELT', $array['maxLat']), 'and');//(`latitude` >= minLat) AND (`latitude` <=maxLat)
                    
                    $row['nearby']    = db('order')
                        ->join('order_info', 'order_info.order_id=order.order_id', 'left')
                        ->whereBetween('order.state',[3,7])
                        ->field('order.order_no as order_id,concat(order_info.province,order_info.city,order_info.county,order.addres) as addres,if(order.logo=10,"https://yiniao.oss-cn-shenzhen.aliyuncs.com/img/1.png","https://yiniao.oss-cn-shenzhen.aliyuncs.com/img/1.png") as log')
                        ->where($condition)->where('order.pro_id', $data['mainId'])->limit(3)->select();
                    $row['data']      = $rows;
                    $row['title']     = $diagnostic_record['title'];
                    $row['reminders'] = $diagnostic_record['reminders'];
                    
                }
                
            }
            
        }
        
        r_date($row, 200);
        
    }
    
    public function getAround($longitude, $latitude, $raidus)
    {
        $PI        = 3.14159265;
        $degree    = (24901 * 1609) / 360.0;
        $dpmLat    = 1 / $degree;
        $radiusLat = $dpmLat * $raidus;
        $minLat    = $latitude - $radiusLat;
        $maxLat    = $latitude + $radiusLat;
        $mpdLng    = $degree * cos($latitude * ($PI / 180));
        $dpmLng    = 1 / $mpdLng;
        $radiusLng = $dpmLng * $raidus;
        $minLng    = $longitude - $radiusLng;
        $maxLng    = $longitude + $radiusLng;
        return array('minLng' => $minLng, 'maxLng' => $maxLng, 'minLat' => $minLat, 'maxLat' => $maxLat);
    }
    
    public static function PosOffset($arr1, $i, $arr2)
    {
        $len2         = count($arr2);
        $arr2_reverse = array_reverse($arr2);
        for ($j = 0; $j < $len2; $j++) {
            $rev_num     = abs($i - $j) - 1;
            $rev_data    = isset($arr2_reverse[$rev_num]) ? $arr2_reverse[$rev_num] : '';
            $notrev_data = isset($arr2[$i - $j]) ? $arr2[$i - $j] : '';
            if ($i + $j >= 0 && $arr1[$i] == ($i - $j >= 0 ? $notrev_data : $rev_data)) {
                return $j;
            }
            if ($i + $j < $len2 && $arr1[$i] == $arr2[$i + $j]) {
                return $j;
            }
        }
        return $len2;
    }
    
    #计算匹配文字$arr1[$i]对于整体相似度的贡献量
    public static function CC($arr1, $i, $arr2)
    {
        $len2       = count($arr2);
        $len2_float = sprintf("%.2f", $len2);
        $temp       = self::PosOffset($arr1, $i, $arr2);
        $data       = ($len2 - $temp) / $len2_float;
        return $data;
    }
    
    #计算短语$arr1相对于短语$arr2的相似度sc
    public static function SC($arr1, $arr2)
    {
        $sc   = 0.0;
        $len1 = count($arr1);
        for ($i = 0; $i < $len1; $i++) {
            $sc += self::CC($arr1, $i, $arr2);
        }
        $sc /= $len1;
        return $sc;
    }
    
    #计算短语$arr1与短语$arr2之间的相似度
    public static function S($arr1, $arr2)
    {
        $temp1 = self::SC($arr1, $arr2);
        $temp2 = self::SC($arr2, $arr1);
        return ($temp1 + $temp2) / 2;
    }
    /*
     * 新版问题匹配方案。
     *
     */
    public function QuestionCategory()
    {
        $re = db('business_category', config('database.zong'))
            ->field('id,name,pid')
            ->where('status', 1)
            ->where('pid', 0)
            ->order('sort aes')
            ->select();
        
        r_date(["title"=>"请选择房屋遇到问题",'children'=>$re], 200);
    }
    /*
     * 新版问题匹配方案。
     *
     */
    public function QuestionCategoryLevel()
    {
        $data    = Authority::param(['id']);
        $re = db('business_category', config('database.zong'))
            ->field('id,name,pid')
            ->where('status', 1)
            ->where('pid', $data['id'])
            ->order('sort aes')
            ->select();
//        $res = db('business_category', config('database.zong'))->where('id', $data['id'])->find();
//        $res = db('business_category', config('database.zong'))
//            ->field('id,name,pid')
//            ->where('status', 1)
//            ->where('pid', $res['pid'])
//            ->order('sort aes')
//            ->select();
        $title="请选择主要类别";
        $id=array_unique(array_column($re,'id'));
        $childrenList = db('business_category', config('database.zong'))
            ->field('id,name,pid')
            ->where('status', 1)
            ->whereIn('pid', $id)
            ->order('sort aes')
            ->select();
        if(empty($childrenList)){
            $title="请选择核心的需求或问题";
        }
        r_date(["title"=>$title,'children'=>$re], 200);
    }
    /*
     * 匹配数据 职匹配最后一级
     */
    public function newMatching(schemeMaster $schemeMaster,SchemeImg $schemeImg,SchemeTag $schemeTag,SchemeCharacteristic $characteristic){
        $data    = Authority::param(['id', 'lat', 'lng', 'order_id','selectedId']);
        $rows = $schemeMaster
            ->with(['schemeProject', 'schemeProject.specsList'])
            ->with('schemeImg')
            ->with('schemeTag')
            ->with('schemeCharacteristic')
            ->where('scheme_master.business_category_id', $data['id'])
            ->where('scheme_master.state', 1)
            ->field('scheme_master.plan_id,scheme_master.name,scheme_master.info,scheme_master.day,scheme_master.reminde,scheme_master.pricing_rules,scheme_master.service_content,scheme_master.materials_used,scheme_master.service_duration,scheme_master.completion,scheme_master.quality')
            ->limit(8)
            ->select();
        $selectedId = json_decode($data['selectedId'], true);
        $row=null;
        $option=implode(",",array_column($selectedId,'id'));
        if ($rows) {
            $time=time();
            foreach ($rows as $k1 => $item) {
                db('scheme_view_log', config('database.zong'))->insert(['city_id'=>config('cityId'),'order_id'=>$data['order_id'],'scheme_id'=>$item['plan_id'],'created_time'=>$time,'option'=>$option]);
                $rows[$k1]['selectType'] = 1;
                $tageList                = [];
                $result = array();
                if ($item['scheme_tag']) {
                    
                    foreach ($item['scheme_tag'] as $k => $v) {
                        $result[$v['pid']][] = $v;
                    }
            
                    foreach ($result as $k => $list) {
                        $schemeTag['id'] = $k;
                
                        $schemeTag['position'] = $result[$k];
                        unset($item['scheme_tag']);
                        $tageList[] = $schemeTag;
                    }
                }
                $result = array();
                if ($item['scheme_project']) {
                    $title  = array_unique(array_column($item['scheme_project'], 'grouping'));
                    
                    foreach ($title as $key => $info) {
                        foreach ($item['scheme_project'] as $it) {
                            $it['specsList'] = $it['specs_list'];
                            $it['allMoney']  = $it['to_price'];
                            $it['types']     = 4;
                            unset($it['specs_list']);
                            if ($info == $it['grouping']) {
                                $result[$key]['title']  = $info;
                                $result[$key]['id']     = 0;
                                $result[$key]['data'][] = $it;
                            }
                    
                        }
                    }
            
                }
        
                unset($item['scheme_project']);
                $item['scheme_project'] = array_merge($result);
        
        
            }
    
            $array                  = $this->getAround($data['lng'], $data['lat'], 5000);
            $condition['order.lng'] = array(array('EGT', $array['minLng']), array('ELT', $array['maxLng']), 'and');//(`longitude` >= minLng) AND (`longitude` <= maxLng)
            $condition['order.lat'] = array(array('EGT', $array['minLat']), array('ELT', $array['maxLat']), 'and');//(`latitude` >= minLat) AND (`latitude` <=maxLat)
            $mainId=db('order')->where('order_id',$data['order_id'])->value('pro_id');
            $row['nearby']    = db('order')
                ->join('order_info', 'order_info.order_id=order.order_id', 'left')
                ->whereBetween('order.state', [3, 7])
                ->field('order.order_no as order_id,concat(order_info.province,order_info.city,order_info.county,order.addres) as addres,if(order.logo=10,"https://yiniao.oss-cn-shenzhen.aliyuncs.com/img/1.png","https://yiniao.oss-cn-shenzhen.aliyuncs.com/img/1.png") as log')
                ->where($condition)->where('order.pro_id', $mainId)->limit(3)->select();
            $row['data']      = $rows;
            $row['title']     = '';
            $row['reminders'] = '';
        }
        $Products=new Products();
        $Product1 =$Products->indexPublic(['productsPosition'=>$data['id'],'page'=>1,'limit'=>5]);
        $row['product']=$Product1;
        r_date($row, 200);
    }

    //children有数据才显示
    public function tree_children($data, $pId = 0)
    {
        $tree = array();
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pId) {
                $child = self::tree_children($data, $v['id']);
                if (count($child)) {
                    $v['children'] = $child;
                }
                $tree[] = $v;
            }
        }
        return $tree;
    }
   /*
     *附近的案例分享
     */
    public function caseSharing()
    {
        $data = Authority::param(['orderId', 'title', 'questionType', 'questionType1']);
        $order = \db('order')->where(['order_id' => $data['orderId']])->find();
        $array = $this->getAround($order['lng'], $order['lat'], 5000);
        $condition = [];
        if ($data['title'] == '') {
            $condition['order.lng'] = array(array('EGT', $array['minLng']), array('ELT', $array['maxLng']), 'and');//(`longitude` >= minLng) AND (`longitude` <= maxLng)
            $condition['order.lat'] = array(array('EGT', $array['minLat']), array('ELT', $array['maxLat']), 'and');//(`latitude` >= minLat) AND (`latitude` <=maxLat)
        } else {
            $condition['order.addres'] = array('like', "%{$data['title']}%");
        }
        if ($data['questionType'] != 0) {
            $condition['order.pro_id'] = $data['questionType'];
        }
        if ($data['questionType1'] != 0) {
            $condition['order.pro_id1'] = $data['questionType1'];
        }
        if ($data['questionType'] != 999 && $data['questionType'] != 998) {
            $auxiliary_delivery_node = \db('auxiliary_delivery_node')->field('count(auxiliary_delivery_schedul_id) as nodeId,auxiliary_delivery_schedul_id')->where('auxiliary_delivery_node.state', 1)->group('auxiliary_delivery_schedul_id')->buildSql();

            $auxiliary_delivery_schedule = \db('auxiliary_delivery_schedule')->field('count(auxiliary_delivery_schedule.id) as scheduleId,sum(nodeId) as nodeIds,node.auxiliary_delivery_schedul_id,auxiliary_delivery_schedule.auxiliary_project_list_id')->join([$auxiliary_delivery_node => 'node'], 'node.auxiliary_delivery_schedul_id=auxiliary_delivery_schedule.id', 'right')->whereNull('auxiliary_delivery_schedule.delete_time')->group('auxiliary_project_list_id')->buildSql();

            $auxiliary_project_list = \db('auxiliary_project_list')->field('sum(node1.scheduleId) as scheduleId,sum(node1.nodeIds) as nodeIds,auxiliary_project_list.order_id')->join([$auxiliary_delivery_schedule => 'node1'], 'node1.auxiliary_project_list_id=auxiliary_project_list.id', 'right')->join('capital', 'capital.capital_id=auxiliary_project_list.capital_id', 'left')->where('capital.types', 1)->where('capital.enable', 1)
                ->whereNotNull('node1.nodeIds')->where('node1.nodeIds', '>', 2)
                ->whereNull('auxiliary_project_list.delete_time')->group('auxiliary_project_list.order_id')->buildSql();
            $row = db('order')->join('order_info', 'order_info.order_id=order.order_id', 'left')->join([$auxiliary_project_list => 'schedule'], 'schedule.order_id=order.order_id', 'right')->join('work_check', 'work_check.order_id=order.order_id and work_check.work_title_id=5 and work_check.delete_time=0', 'right')->where('order.state', '>', 3)->group('order.order_id')->where(function ($quer) {
                $quer->where(function ($que) {
                    $que->where('work_check.img', '<>', '')->where('work_check.img', 'EXP', 'IS NOT NULL');
                })->whereOr(function ($quey) {
                    $quey->where('work_check.no_watermark_image', '<>', '')->where('work_check.no_watermark_image', 'EXP', 'IS NOT NULL');
                });
            })->where('JSON_LENGTH(if(work_check.img !="" and work_check.img IS NOT NULL,work_check.img,work_check.no_watermark_image))>=3')->field('order.order_id as orderId,if(order.assignor=' . $this->us['user_id'] . ',"我的工地","") as my,order_info.pro_id_title as title,if(work_check.img !="" and work_check.img IS NOT NULL,work_check.img,work_check.no_watermark_image) as img,order.lat,order.lng,FROM_UNIXTIME(order.finish_time,"%Y%m%d") as finish_time,order.addres,if(order.state=4,"施工中","已完工") as state,sum(schedule.scheduleId) as s1,sum(schedule.nodeIds) as s')->order('order.cleared_time desc')->where($condition)->select();
        } elseif ($data['questionType'] == 998) {

            $rowList = db('premium_case', config('database.zong'))
                ->field('image as img, title, address as addres, tag, id as orderId,price,space_category_id')
                ->where('status', 1)
                ->select();
            $row = [];
            if ($data['title'] != '') {
                $user_config = db('user_config', config('database.zong'))->where('key', 'quotation_template')->value('value');
                $user_config = json_decode($user_config, true);
                foreach ($rowList as $key => $value) {
                    $space_category_id = json_decode($value['space_category_id'], true);
                    foreach ($space_category_id as $key => $v) {
                        foreach ($user_config as $key => $item) {

                            if (strpos($item['title'], $data['title']) !== false && $v == $item['id']) {
                                array_push($row, $value);
                                break;
                            }# code...
                        }
                    }
                    
                    $price=explode("-",$value['price']);
                    if (is_array($price) && ((count($price)>1 &&$price[0]<= $data['title'] && $price[1]>=$data['title'])|| (count($price)==1 &&strpos($price[0], $data['title']) !== false))) {

                        array_push($row, $value);
                    }
                    $tag = json_decode($value['tag'], true);
                    foreach ($tag as $key => $item) {
                        if (strpos($item, $data['title']) !== false) {
                            array_push($row, $value);
                            break;
                        }# code...
                    }

                }

            } else {
                $row = $rowList;
            }

        } else {
            $condition1['order.addres'] = array('like', "%{$data['title']}%");
            $auxiliary_delivery_node = \db('auxiliary_delivery_node')->field('count(auxiliary_delivery_schedul_id) as nodeId,auxiliary_delivery_schedul_id')->where('auxiliary_delivery_node.state', 1)->group('auxiliary_delivery_schedul_id')->buildSql();

            $auxiliary_delivery_schedule = \db('auxiliary_delivery_schedule')->field('count(auxiliary_delivery_schedule.id) as scheduleId,sum(nodeId) as nodeIds,node.auxiliary_delivery_schedul_id,auxiliary_delivery_schedule.auxiliary_project_list_id')->join([$auxiliary_delivery_node => 'node'], 'node.auxiliary_delivery_schedul_id=auxiliary_delivery_schedule.id', 'right')->whereNull('auxiliary_delivery_schedule.delete_time')->group('auxiliary_project_list_id')->buildSql();

            $auxiliary_project_list = \db('auxiliary_project_list')->field('sum(node1.scheduleId) as scheduleId,sum(node1.nodeIds) as nodeIds,auxiliary_project_list.order_id')->join([$auxiliary_delivery_schedule => 'node1'], 'node1.auxiliary_project_list_id=auxiliary_project_list.id', 'right')->join('capital', 'capital.capital_id=auxiliary_project_list.capital_id', 'left')->where('capital.types', 1)->where('capital.enable', 1)
                ->whereNotNull('node1.nodeIds')->where('node1.nodeIds', '>', 2)
                ->whereNull('auxiliary_project_list.delete_time')->group('auxiliary_project_list.order_id')->buildSql();
            $row = db('order')->join('order_info', 'order_info.order_id=order.order_id', 'left')->join([$auxiliary_project_list => 'schedule'], 'schedule.order_id=order.order_id', 'right')->join('work_check', 'work_check.order_id=order.order_id and work_check.work_title_id=5 and work_check.delete_time=0', 'right')->where('order.state', '>', 3)->group('order.order_id')->where(function ($quer) {
                $quer->where(function ($que) {
                    $que->where('work_check.img', '<>', '')->where('work_check.img', 'EXP', 'IS NOT NULL');
                })->whereOr(function ($quey) {
                    $quey->where('work_check.no_watermark_image', '<>', '')->where('work_check.no_watermark_image', 'EXP', 'IS NOT NULL');
                });
            })->where('JSON_LENGTH(if(work_check.img !="" and work_check.img IS NOT NULL,work_check.img,work_check.no_watermark_image))>=3')->field('order.order_id as orderId,if(order.assignor=' . $this->us['user_id'] . ',"我的工地","") as my,order_info.pro_id_title as title,if(work_check.img !="" and work_check.img IS NOT NULL,work_check.img,work_check.no_watermark_image) as img,order.lat,order.lng,FROM_UNIXTIME(order.finish_time,"%Y%m%d") as finish_time,order.addres,if(order.state=4,"施工中","已完工") as state,sum(schedule.scheduleId) as s1,sum(schedule.nodeIds) as s')->order('order.cleared_time desc')->where('grade', 'A')->where($condition1)->select();
        }

        foreach ($row as $k => $item) {
            $row[$k]['distance'] = "";
            $row[$k]['distances'] = 0;
            if (isset($item['lat']) && $item['lat'] != 0) {
                $Difference = getDistance($item['lat'], $item['lng'], $order['lat'], $order['lng']);
                $row[$k]['distance'] = "距离" . ($Difference / 1000) . "km";
                $row[$k]['distances'] = $Difference / 1000;
            }
            $pattern = '/(\d{2,})/';
            $replacements = preg_replace($pattern, str_repeat('*', 1), $item['addres']);

            $pattern = '/(\d+)/';
            $replacement = '*';
            $newAddress = preg_replace($pattern, $replacement, $replacements);
            $row[$k]['addres'] = $newAddress;
            if (isset($item['finish_time'])) {
                $row[$k]['addres'] = $item['finish_time'] . $row[$k]['addres'];
            }
            if ($data['questionType'] == 998) {
                $row[$k]['type'] = 3;
                $row[$k]['addres'] = $item['title'];
                $row[$k]['title'] = $newAddress;
            } elseif ($data['questionType'] == 999) {
                $row[$k]['type'] = 1;
            } else {
                $row[$k]['type'] = 1;
            }
            if (isset($item['tag'])) {
                $row[$k]['tag'] = json_decode($item['tag'], true);
            }

            unset($item['finish_time']);
            $row[$k]['img'] = json_decode($item['img'], true)[0];
        }
        $Visa = new Visa();
        $row = $Visa->arraySort($row, 'distances', SORT_ASC);

        r_date($row);
    }

    /*
     * 案例详情
     */
    public function caseSharingInfo()
    {
        $data = Authority::param(['orderId']);
        $auxiliary_delivery_node = \db('auxiliary_delivery_node')->field(" CONCAT('[', GROUP_CONCAT(JSON_OBJECT('creationTime',FROM_UNIXTIME(auxiliary_delivery_node.upload_time,'%Y-%m-%d'),'node_id',auxiliary_delivery_node.node_id) SEPARATOR ','), ']') as  content,auxiliary_delivery_node.auxiliary_delivery_schedul_id")->where('auxiliary_delivery_node.state', 1)->group('auxiliary_delivery_schedul_id')->buildSql();

        $auxiliary_delivery_schedule = \db('auxiliary_delivery_schedule')->field("CONCAT('[', GROUP_CONCAT(JSON_OBJECT('title',CONCAT(capital.class_b,'-',auxiliary_interactive.title),'list',node.content) SEPARATOR ','), ']') as  content,capital.class_b")->join([$auxiliary_delivery_node => 'node'], 'node.auxiliary_delivery_schedul_id=auxiliary_delivery_schedule.id', 'right')->join('auxiliary_project_list', 'auxiliary_project_list.id=auxiliary_delivery_schedule.auxiliary_project_list_id', 'left')->join('auxiliary_interactive', 'auxiliary_interactive.id=auxiliary_delivery_schedule.auxiliary_interactive_id', 'left')->join('capital', 'capital.capital_id=auxiliary_project_list.capital_id', 'left')->where('capital.types', 1)->where('capital.enable', 1)->where('auxiliary_project_list.order_id', $data['orderId'])->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->group('auxiliary_project_list_id')->select();
        $listArray = [];
        foreach ($auxiliary_delivery_schedule as $k => $item) {
            $content = json_decode($item['content'], true);
            $lists['img'] = [];
            foreach ($content as $l => $value) {
                $list = json_decode($value['list'], true);

                foreach ($list as $b => $val) {

                    $val['title'] = $value['title'];
                    $lists['img'][] = $val;
                }

                $lists['title'] = $item['class_b'];
            }

            $listArray[] = $lists;
        }
        foreach ($listArray as $k => $l) {
            $paths = [];
            foreach ($l['img'] as $v => $item) {
                $pathId = db('app_user_order_node')->whereIn('app_user_order_node.id', $item['node_id'])->column('resource_ids');
                if (!empty($pathId)) {
                    $common_resourceID = '';
                    foreach ($pathId as $o) {
                        $common_resourceID .= $o;
                    }
                    $path = db('common_resource')->where('status', 1)->whereIn('id', $common_resourceID)->field('mime_type,path,id')->select();
                    foreach ($path as $k1 => $o) {
                        $imglist['img'] = 'https://images.yiniao.co/' . $o['path'];
                        $imglist['title'] = $item['title'];
                        $imglist['creationTime'] = $item['creationTime'];
                        $paths[] = $imglist;
                    }
                }

                $listArray[$k]['date'] = $paths;
                unset($listArray[$k]['img']);
                $listArray[$k]['img'] = empty($paths) ? '' : $paths[0]['img'];

            }

            if (count($listArray[$k]['date']) <= 1) {
                unset($listArray[$k]);
            }

        }
        $listArray = array_merge($listArray);
        $workCheckImg = [];
        $row = db('order')->join('order_info', 'order_info.order_id=order.order_id', 'left')->join('order_aggregate', 'order_aggregate.order_id=order.order_id', 'left')->join('work_check', 'work_check.order_id=order.order_id and work_check.work_title_id=5 and work_check.delete_time=0', 'right')->where('order.state', '>=', 4)->where('order.state', '<', 8)->where('order.order_id', $data['orderId'])->field('order.addres,if(work_check.img !="" and work_check.img IS NOT NULL,work_check.img,work_check.no_watermark_image) as img,order_aggregate.total_price,order_info.gong,FROM_UNIXTIME(work_check.creation_time,"%Y-%m-%d") as creation_time')->order('order.cleared_time desc')->find();
        $handover = db('startup_handover')->join('startup', 'startup_handover.startup_id=startup.startup_id', 'left')->where('startup.orders_id', $data['orderId'])->field('startup_handover.img_url as img,FROM_UNIXTIME(startup.created_time,"%Y-%m-%d") as created_time')->select();
        $kai = db('app_user_order_node')->where('status', 1)->where('type', 1)->where('app_user_order_node.order_id', $data['orderId'])->whereNull('deleted_at')->field('app_user_order_node.resource_ids,FROM_UNIXTIME(app_user_order_node.created_at,"%Y-%m-%d") as creationTime')->select();
        $work = json_decode($row['img'], true);
        foreach ($work as $k => $item) {
            $workCheckImg[$k]['title'] = '完工验收';
            $workCheckImg[$k]['img'] = $item;
            $workCheckImg[$k]['creationTime'] = $row['creation_time'];
        }
        $workCheckImgList['title'] = '完工验收';
        $workCheckImgList['img'] = $workCheckImg[0]['img'];
        $workCheckImgList['date'] = $workCheckImg;
        //开工图片
        if (!empty($kai)) {
            $kaiImgList = [];
            foreach ($kai as $k => $l) {
                $kaiPath = db('common_resource')->where('status', 1)->whereIn('id', $l['resource_ids'])->field('mime_type,path,id')->select();
                foreach ($kaiPath as $o) {
                    $kaiList['img'] = 'https://images.yiniao.co/' . $o['path'];
                    $kaiList['title'] = '开工';
                    $kaiList['creationTime'] = $l['creationTime'];
                    $kaiImgList[] = $kaiList;
                }
            }
            if (count($kaiImgList) > 1) {
                $startWork['title'] = '开工';
                $startWork['img'] = $kaiImgList[0]['img'];
                $startWork['date'] = $kaiImgList;
                array_unshift($listArray, $startWork);
            }

        }
        //交底图片
        if (!empty($handover) && count($handover) > 1) {
            $handoverImg = array_column($handover, 'img');
            foreach ($handoverImg as $k => $item) {
                $handoverListImg[$k]['title'] = '交底方案';
                $handoverListImg[$k]['img'] = $item;
                $handoverListImg[$k]['creationTime'] = $handover[0]['created_time'];
            }

            $handoverList['title'] = '交底方案';
            $handoverList['img'] = $handoverListImg[0]['img'];
            $handoverList['date'] = $handoverListImg;
            array_unshift($listArray, $handoverList);
        }

        array_push($listArray, $workCheckImgList);
        $listArray = array_merge($listArray);
        $pattern = '/(\d{2,})/';
        $replacements = preg_replace($pattern, str_repeat('*', 1), $row['addres']);

        $pattern = '/(\d+)/';
        $replacement = '*';
        $newAddress = preg_replace($pattern, $replacement, $replacements);
        $listDate['addres'] = $newAddress;

        $budget = strlen((string) (int) $row['total_price']);
        $step = 0;
        if ($budget == 3) {
            $step = 100;
        } elseif ($budget == 4) {
            $step = 1000;
        } elseif ($budget == 5) {
            $step = 10000;
        } elseif ($budget == 6) {
            $step = 100000;
        }
        $listDate['budget'] = '一万以内';
        if ($row['total_price'] > 10000) {
            $budgetList = $this->numberToInterval($row['total_price'], $step);
            $listDate['budget'] = $budgetList[0] . '至' . $budgetList[1];
        }

        $listDate['gong'] = $row['gong'] . '工作日';
        $listDate['list'] = $listArray;

        r_date($listDate);
    }
    /*
     * 精品案例
     */
    public function caseSharingPremiumInfo()
    {
        $data = Authority::param(['orderId']);
        $row = db('premium_case', config('database.zong'))->join('goods_category', 'goods_category.id=premium_case.goods_category_id_1', 'left')->join('goods_category goods_category1', 'goods_category1.id=premium_case.goods_category_id_2', 'left')->field('premium_case.image as img,premium_case.title,premium_case.address,premium_case.tag,concat(goods_category.title,"-",goods_category1.title) as goodsCategoryTitle,premium_case.desc,premium_case.space_category_id,premium_case.price')->where('status', 1)->where('premium_case.id', $data['orderId'])->find();
        $space_category_id = json_decode($row['space_category_id'], true);
        $user_config = db('user_config', config('database.zong'))->where('key', 'quotation_template')->value('value');
        $user_config = json_decode($user_config, true);
        $space_categoryList = [];
        foreach ($space_category_id as $item) {
            foreach ($user_config as $value) {
                if ($value['id'] == $item) {
                    $space_categoryList[] = $value['title'];
                }
            }

        }
        $row['img'] = json_decode($row['img'], true);
        $row['tag'] = json_decode($row['tag'], true);
        $row['spaceCategoryList'] = $space_categoryList;
        unset($row['space_category_id']);
        r_date($row);
    }


    function numberToInterval($number, $step)
    {
        $start = floor($number / $step) * $step; // 区间的开始
        $end = $start + $step; // 区间的结束
        return array($start, $end);
    }

    /*
     * 分享
     */
    public function share()
    {
        $data = Authority::param(['orderId', 'orderIdList']);
        $orderIdList = json_decode($data['orderIdList'], true);
        $case_order_id = [];
        $premium_case_id = [];
        foreach ($orderIdList as $item) {
            if ($item['type'] == 1) {
                $case_order_id[] = $item['orderId'];
            }
            if ($item['type'] == 3) {
                $premium_case_id[] = $item['orderId'];
            }
        }
        $id = db('case_share', config('database.zong'))->insertGetId(['user_id' => $this->us['user_id'], 'share_order_id' => $data['orderId'], 'case_order_id' => implode(",", $case_order_id), 'premium_case_id' => implode(",", $premium_case_id), 'create_time' => time()]);
        r_date(['id' => $id, 'url' => 'https://member-system-190zk-1304877581.tcloudbaseapp.com/nearbySites.html?case_share_id=' . $id], 200);
    }

    /*
     * 分享记录
     */
    public function shareRecord()
    {
        $case_share = db('case_share', config('database.zong'))->join('order', 'case_share.share_order_id=order.order_id', 'left')->field('order.contacts,order.addres,case_share.id,case_share.case_order_id,case_share.user_share_count as userShareCount,case_share.user_open_count as userOpenCount,case_share.id,case_share.share_order_id,FROM_UNIXTIME(case_share.create_time,"%Y-%m-%d") as creation_time,case_share.id,case_share.user_browse_duration,case_share.premium_case_id')->where(['case_share.user_id' => $this->us['user_id']])->order('case_share.create_time desc')->select();
        $case_share_view = db('case_share_view', config('database.zong'))->join('order', 'case_share_view.case_order_id=order.order_id', 'right')->field('order.addres,case_share_view.case_share_id,case_share_view.user_browse_duration')->whereIn('case_share_id', array_column($case_share, 'id'))->select();
        $case_share_viewPremiumCase = db('case_share_view', config('database.zong'))->join('premium_case', 'case_share_view.premium_case_id=premium_case.id', 'right')->field('premium_case.address as addres,case_share_view.case_share_id,case_share_view.user_browse_duration')->whereIn('case_share_id', array_column($case_share, 'id'))->where('premium_case_id', '<>', 0)->select();
        $case_share_view = array_merge($case_share_view, $case_share_viewPremiumCase);
        foreach ($case_share as $k => $item) {
            //分享个数
            $case_share[$k]['numberOfShares'] = count(explode(',', $item['case_order_id'])) + count(explode(',', $item['premium_case_id']));
            //浏览最多
            $mostViewed = [];
            foreach ($case_share_view as $v) {
                if ($item['id'] == $v['case_share_id']) {
                    $mostViewed[] = $v;
                }
            }
            $mostViewedCount = array_column($mostViewed, 'addres');
            $arr = array_count_values($mostViewedCount);   // 统计数组中所有值出现的次数
            arsort($arr);                                   // 按照键值对数组进行降序排序
            $more_value = key($arr);           //出现次数最多的值
            $pattern = '/(\d{2,})/';
            $replacements = preg_replace($pattern, str_repeat('*', 1), $item['addres']);

            $pattern = '/(\d+)/';
            $replacement = '*';
            $newAddress = preg_replace($pattern, $replacement, $replacements);
            $case_share[$k]['addres'] = $newAddress;
            $case_share[$k]['userBrowseDuration'] = empty($item['user_browse_duration']) ? 0 : round($item['user_browse_duration'] / 60, 2);

            $replacements1 = preg_replace($pattern, str_repeat('*', 1), $more_value);
            $newAddress1 = preg_replace($pattern, $replacement, $replacements1);
            $case_share[$k]['mostViewed'] = $newAddress1;
            $case_share[$k]['numberBrowseScheme'] = count(array_unique(array_column($mostViewed, 'addres')));
            unset($case_share[$k]['case_order_id'], $case_share[$k]['share_order_id']);
        }
        $tageList = null;
        $result = [];
        foreach ($case_share as $k => $v) {
            $result[$v['creation_time']][] = $v;
        }
        foreach ($result as $k => $list) {
            $schemeTag['title'] = $k;
            $schemeTag['data'] = $result[$k];
            $tageList[] = $schemeTag;
        }
        r_date($tageList, 200);
    }
    /*
     * 分享记录详情
     */
    public function shareRecordInfo()
    {
        $data = Authority::param(['id']);
        $case_share = db('case_share', config('database.zong'))->join('order', 'order.order_id=case_share.share_order_id', 'left')->field('order.lat,order.lng,case_share.case_order_id,case_share.create_time,case_share.premium_case_id')->where(['id' => $data['id']])->find();
        $row = db('order')->join('order_info', 'order_info.order_id=order.order_id', 'left')
            ->whereIn('order.order_id', $case_share['case_order_id'])->where('order.state', '>', 3)->group('order.order_id')
            ->field('order.order_id as orderId,if(order.assignor=' . $this->us['user_id'] . ',"我的工地","") as my,order_info.pro_id_title as title,order.lat,order.lng,FROM_UNIXTIME(order.finish_time,"%Y%m%d")as addres,order.addres as sss,if(order.state=4,"施工中","已完工") as state')->order('order.cleared_time desc')->select();
        $case_share_view = db('case_share_view', config('database.zong'))->where('case_share_id', $data['id'])->select();
        foreach ($row as $k => $item) {
            $Difference = getDistance($item['lat'], $item['lng'], $case_share['lat'], $case_share['lng']);
            $row[$k]['distance'] = "距离" . ($Difference / 1000) . "km";
            $row[$k]['distances'] = $Difference / 1000;
            $open = 0;
            $Browseduration = [];
            foreach ($case_share_view as $o) {
                if ($o['case_order_id'] == $item['orderId']) {
                    $open += 1;
                    $Browseduration[] = $o;
                }
            }
            $pattern = '/(\d{2,})/';
            $replacements = preg_replace($pattern, str_repeat('*', 1), $item['sss']);

            $pattern = '/(\d+)/';
            $replacement = '*';
            $newAddress = preg_replace($pattern, $replacement, $replacements);
            $row[$k]['addres'] = $item['addres'] . $newAddress;
            $row[$k]['userBrowseDuration'] = empty($Browseduration) ? 0 : array_sum(array_column($Browseduration, 'user_browse_duration'));
            $row[$k]['open'] = $open;
            $row[$k]['type'] = 1;
            $row[$k]['browseduration'] = empty($Browseduration) ? '' : date('Y-m-d H:i:s', max(array_column($Browseduration, 'create_time')));
            $work_check = db('work_check')->where(['work_check.work_title_id' => 5, 'work_check.delete_time' => 0])->where('order_id', $item['orderId'])->field('if(work_check.img !="" and work_check.img IS NOT NULL,work_check.img,work_check.no_watermark_image) as img')->find();
            $row[$k]['img'] = json_decode($work_check['img'], true)[0];
            unset($row[$k]['sss']);
        }
        if ($case_share['premium_case_id'] != '' && $case_share['premium_case_id'] != 0) {
            $rowPremiumCase = db('premium_case', config('database.zong'))->field('image as img,title,address as addres,tag,id as orderId')->where('status', 1)->where('city_id', config('cityId'))->whereIn('id', $case_share['premium_case_id'])->select();
            foreach ($rowPremiumCase as $k => $item) {

                $rowPremiumCase[$k]['distance'] = "";
                $rowPremiumCase[$k]['distances'] = 0;
                $open = 0;
                $Browseduration = [];
                foreach ($case_share_view as $o) {
                    if ($o['premium_case_id'] == $item['orderId']) {
                        $open += 1;
                        $Browseduration[] = $o;
                    }
                }
                $pattern = '/(\d{2,})/';
                $replacements = preg_replace($pattern, str_repeat('*', 1), $item['addres']);

                $pattern = '/(\d+)/';
                $replacement = '*';
                $newAddress = preg_replace($pattern, $replacement, $replacements);
                $rowPremiumCase[$k]['addres'] = $item['title'];
                $rowPremiumCase[$k]['title'] = $newAddress;
                $rowPremiumCase[$k]['userBrowseDuration'] = empty($Browseduration) ? 0 : array_sum(array_column($Browseduration, 'user_browse_duration'));
                $rowPremiumCase[$k]['open'] = $open;
                $rowPremiumCase[$k]['browseduration'] = empty($Browseduration) ? '' : date('Y-m-d H:i:s', max(array_column($Browseduration, 'create_time')));
                $rowPremiumCase[$k]['type'] = 3;
                $rowPremiumCase[$k]['img'] = json_decode($item['img'], true)[0];
                $rowPremiumCase[$k]['tag'] = json_decode($item['tag'], true);

            }
            $row = array_merge($rowPremiumCase, $row);
        }


        $Visa = new Visa();
        $row = $Visa->arraySort($row, 'distances', SORT_ASC);
        r_date($row, 200);
    }
}